package com.apestech.framework.db.session;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.SqlParam;
import com.apestech.framework.sql.SqlUtil;
import com.apestech.framework.sql.lib.TableSql;
import com.apestech.framework.xml.plugin.XmlPaste;
import com.apestech.framework.xml.plugin.modul.QryConfig;
import com.apestech.framework.xml.table.modul.Tables;

import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @author hup
 * @create 2018-08-31-11:58
 */
public class SessionUtil extends SqlUtil {

    public class Sql{
        private String printSql;
        private String execSql;
        private JSONArray param;
        public Sql(String printSql, String execSql, JSONArray param){
            this.printSql=printSql;
            this.execSql=execSql;
            this.param=param;
        }

        public String getPrintSql() {
            return printSql;
        }

        public String getExecSql() {
            return execSql;
        }

        public JSONArray getParam() {
            return param;
        }
    }

    public SqlParam getQueryParam(SqlSession session, JSONObject param, QryConfig qryConfig) throws Exception{
        SqlParam sqlparam=new SqlParam(session);
        if(param==null) {
            throw new Exception("研发相关入参不允许为空！");
        }
        sqlparam.setSqlInput(param, qryConfig);
        sqlparam.expain();
        return sqlparam;
    }

    public String getQueryParamSql(SqlSession session, JSONObject param) throws Exception{
        if(param==null) {
            throw new Exception("研发相关入参不允许为空！");
        }
        SqlParam sqlparam=new SqlParam(session);
        sqlparam.setSqlInput(param, null);
        return sqlparam.getXmlsql();
    }

    public JSONObject setQueryId(String xmlId, String sqltype, JSONObject param){
        if(param==null) param=new JSONObject();
        if(param.get("queryid")==null) param.put("queryid", xmlId);
        if(param.get("sqltype")==null) param.put("sqltype", sqltype);
        param.remove("nb_table");
        param.remove("nb_sql");
        param.remove("nb_from");
        param.remove("autoCompletion");
        return param;
    }

    public JSONObject setTablesId(String tablesId, JSONObject param){
        if(param==null) param=new JSONObject();
        if(param.get("tablesid")==null) param.put("tablesid", tablesId);
        param.remove("nb_table");
        param.remove("nb_sql");
        param.remove("nb_from");
        param.remove("autoCompletion");
        return param;
    }

    public JSONObject setTableId(String tableId, JSONObject param){
        if(param==null) param=new JSONObject();
        if(param.get("tableid")==null) param.put("tableid", tableId);
        param.remove("nb_table");
        param.remove("nb_sql");
        param.remove("nb_from");
        param.remove("autoCompletion");
        return param;
    }

    public JSONObject setSql(String sql, String fromtab, String autoCompletion, JSONObject param) {
        if(param==null) param=new JSONObject();
        if(param.get("nb_sql")==null)
            param.put("nb_sql", sql);
        if(param.get("nb_from")==null) param.put("nb_from", fromtab);
        if(param.get("autoCompletion")==null) param.put("autoCompletion", autoCompletion);
        String s=sql.toUpperCase();
        if(s.indexOf("UPDATE")>=0) param.put("sqltype","update");
        else if(s.indexOf("INSERT")>=0) param.put("sqltype","insert");
        else if(s.indexOf("DELETE")>=0) param.put("sqltype","delete");
        param.remove("nb_table");
        param.remove("queryid");
        return param;
    }

    public JSONObject setTableSql(String tabName, String sqltype, String autoCompletion, String filter, boolean in, JSONObject param) {
        if(param==null) param=new JSONObject();
        String sin="0";
        if(in) sin="1";
        if(param.get("nb_table")==null) param.put("nb_table", tabName);
        if(param.get("nb_from")==null) param.put("nb_from", tabName);
        if(param.get("sqltype")==null) param.put("sqltype", sqltype);
        if(param.get("table_filter")==null) param.put("table_filter", filter);
        if(param.get("table_in")==null) param.put("table_in", sin);
        if(param.get("autoCompletion")==null) param.put("autoCompletion", autoCompletion);
        param.remove("nb_sql");
        param.remove("queryid");
        return param;
    }

    public JSONObject addCol(String id, String type, boolean notnull, String defaultValue, String name, boolean iskey){
        JSONObject map=new JSONObject();
        map.put("id", id);
        map.put("type", type);
        map.put("notnull", notnull);
        map.put("default", defaultValue);
        map.put("name", name);
        map.put("key", iskey);
        return map;
    }

    public TableSql getTablesSql(Tables table, SqlSession session) throws Exception {
        TableSql ddl=new TableSql(session);
        ddl.setTable(table);
        return ddl;
    }

    public TableSql getTablesSql(String tableId, SqlSession session) throws Exception {
        XmlPaste xml=new XmlPaste(tableId, "tables", session);
        xml.expain();
        return getTablesSql(xml.getTable(), session);
    }

    public void printSqlList(ArrayList<String> sql){
        int len=sql.size();
        for(int i=0; i<len; i++){
            System.out.println(sql.get(i)+";");
        }
    }

    public String getTwoTableInsert(String stabname, String dtabname, SqlSession session) throws Exception {
        Table stab=session.getDictTable(stabname);
        Table dtab=session.getDictTable(dtabname);
        if(stab==null || dtab==null) return null;
        ArrayList<String> skeylist=stab.getField().getKeylist();
        ArrayList<String> dkeylist=dtab.getField().getKeylist();
        int len=skeylist.size();
        String col="";
        for(int i=0;i<len;i++){
            String key=skeylist.get(i);
            if(dkeylist.contains(key)){
                if(!"".equals(col)){
                    col=col+",";
                }
                col=col+key;
            }
        }
        if("".equals(col)) return null;
        return " INSERT INTO "+dtabname+" ("+col+") SELECT "+col+" FROM "+stabname;
    }


//	public JSONObject queryByIdToJson(String queryId, JSONObject param) throws Exception {
//		boolean array=false;
//		if(param!=null){
//			if(param.get("result_array")!=null){
//				array=param.getBoolean("result_array");
//			}
//		}
//		JSONObject result=new JSONObject();
//    	//获取SQL这块逻辑将从XML配置中获取
//    	JSONArray list=queryById(queryId, param);
//    	if(list.size()==0){
//    		return null;
//		}
//    	if(array){
//    		result.put("P_SELF", list);
//		} else {
//    		return (JSONObject) list.get(0);
//		}
//		return result;
//	}

//	public JSONObject pricingProcess(JSONObject param) throws Exception {
//		boolean array=param.getBoolean("result_array");
//		JSONObject result=new JSONObject();
//		String pricingProcessId=param.getString(NodeVar.PRICING_PROCESS_ID);
//		//获取定价过程ID这块逻辑将从XML配置中获取
//		//定价过程执行入参必须要传connection, 不走SERVICE方式执行，SERVICE方式需要通过SQLSESSION去包一层执行
//		return result;
//	}
//
//	public JSONObject condition(JSONObject param) throws Exception {
//		boolean array=param.getBoolean("result_array");
//		JSONObject result=new JSONObject();
//		String conditionId=param.getString(NodeVar.CONDITION_ID);
//		//获取条件类型ID这块逻辑将从XML配置中获取
//		//条件类型过程执行入参必须要传connection, 不走SERVICE方式执行，SERVICE方式需要通过SQLSESSION去包一层执行
//		return result;
//	}


//	/**
//	 * 以每次提交方式批量执行各类不同SQL，入参格式有要求
//	 * @params params包括内容 sql要求必须为执行SQL，param为执行顺序类参数
//	 * @throws Exception
//	 */
//	public int[] batchUpdate(JSONArray params) throws Exception{
//		int len=params.size();
//		if(len<0) return null;
//		int[] a = new int[len];
//		for(int i=0; i<len; i++){
//			JSONObject map=(JSONObject) params.get(i);
//			String sql=map.getString("sql");
//			JSONObject p=map.getJSONObject("param");
//			if(p!=null){
//				a[i]=update(sql, p);
//			} else {
//				a[i]=update(sql);
//			}
//		}
//		return a;
//	}
//
//	public int[] batchUpdate(ArrayList<String> sqls) throws Exception{
//		return this.cn.batchUpdate(sqls);
//	}
//
//	public int[] batchUpdate(String sql, JSONArray params) throws Exception{
//		int len=params.size();
//		if(len<0) return null;
//		ArrayList<JSONArray> plist=new ArrayList<JSONArray>();
//		SqlParam query=getQueryParam(sql, (JSONObject)params.get(0));
//		System.out.println(query.getSql());
//		System.out.println();
//		JSONArray param=query.getParams();
//		plist.add(param);
//		for(int i=1; i<len; i++){
//			JSONObject input=(JSONObject) param.get(i);
//			JSONArray mxlist=new JSONArray();
//			int plen=param.size();
//			StringBuilder sb=new StringBuilder();
//			sb.append("{");
//			for(int p=0; p<plen; p++){
//				JSONObject sour=(JSONObject) param.get(p);
//				JSONObject dist=new JSONObject(sour);
//				String type=dist.getString("type");
//				String key=dist.getString("key");
//				sb.append(key+":");
//				switch(type){
//					case "VARCHAR2":
//						dist.put("value", input.getString(key));
//						sb.append(input.getString(key));
//						break;
//					case "BIG":
//						dist.put("value", input.getBigDecimal(key));
//						sb.append(input.getString(key));
//						break;
//					case "DATE":
//						Date date=castToDate(input.get("value"));
//						dist.put("value", date.getTime());
//						sb.append(DateUtil.dateTimeToStr(date));
//						break;
//				}
//				if(p>0){
//					sb.append(",");
//				}
//				mxlist.add(dist);
//				sb.append("}");
//				System.out.println(sb.toString());
//				System.out.println();
//			}
//			plist.add(mxlist);
//		}
//		return this.cn.batchUpdate(query.getExecSql(), plist);
//	}
//
//	public JSONObject callProc(String sql, JSONObject param)throws Exception{
//		SqlParam query=getQueryParam(sql, param);
//		System.out.println(query.getPrintSql());
//		System.out.println();
//		return this.cn.callProc(sql, query.getParams());
//	}
//
//	public void callProc(String sql) throws Exception{
//		System.out.println(sql);
//		System.out.println();
//		this.cn.callProc(sql);
//	}


}
